package com.dxt.rabbitmq.service.DelayAndDead;

import com.dxt.rabbitmq.config.DelayAndDeadConfig;
import com.dxt.rabbitmq.vo.TestMessage;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DADPublisher {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void publish(TestMessage testMessage){
        //消息确认
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean b, String s) {
                if(b){
                    System.out.println("message to exchange success.");
                }else{
                    System.out.println("message to exchange failed.");
                }
            }
        });
        //消息返回，当消息从交换机发送到队列失败时执行
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {
                System.out.println("message from exchange to queue failed");
            }
        });
        // 发送消息
        rabbitTemplate.convertAndSend(DelayAndDeadConfig.DELAY_EXCHANGE, DelayAndDeadConfig.DELAY_ROUTING_KEY, testMessage);
    }
}
